package com.whty.demo.utils;

import java.io.UnsupportedEncodingException;
import java.util.Locale;

public class StringUtil {
	
	private static String hexString = "0123456789ABCDEF"; 
	
	/** 
	* 将字符串转成unicode 
	* @param str 待转字符串 
	* @return unicode字符串 
	*/ 
	public static String convert(String str) 
	{ 
		str = (str == null ? "" : str); 
		String tmp; 
		StringBuffer sb = new StringBuffer(1000); 
		char c; 
		int i, j; 
		sb.setLength(0); 
		for (i = 0; i < str.length(); i++) 
		{ 
			c = str.charAt(i); 
			//sb.append("\\u"); 
			j = (c >>>8); //取出高8位 
			tmp = Integer.toHexString(j); 
			if (tmp.length() == 1) 
				sb.append("0"); 
				sb.append(tmp); 
				j = (c & 0xFF); //取出低8位 
				tmp = Integer.toHexString(j); 
			if (tmp.length() == 1) 
				sb.append("0"); 
			sb.append(tmp); 
		} 
		return (new String(sb)); 
	} 
	   
    public static String encodeCN(String data) {  
        byte[] bytes;  
        try {  
            bytes = data.getBytes("gbk");  
            StringBuilder sb = new StringBuilder(bytes.length * 2);  
  
            for (int i = 0; i < bytes.length; i++) {  
                sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));  
                sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));  
            }  
            return sb.toString();  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        }  
        return "";  
    }  
      
    public static String encodeStr(String data) {  
        String result = "";  
        byte[] bytes;  
        try {  
            bytes = data.getBytes("gbk");  
            for (int i = 0; i < bytes.length; i++) {  
                result += Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1);  
            }  
            return result;  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        }  
        return "";  
    }  
      
    /** 
     * 判定是否为中文汉字 
     * @param data 
     * @return 
     */  
    public static boolean isCN(String data) {  
        boolean flag = false;  
        String regex = "^[\u4e00-\u9fa5]*$";  
        if (data.matches(regex)) {  
            flag = true;  
        }  
        return flag;  
    }  
 
    
    /**
     * 中文汉字及字符转为十六进制
     * @param targetStr
     * @return
     */
    public static String getHexResult(String targetStr) {  
        StringBuilder hexStr = new StringBuilder();  
        int len = targetStr.length();  
        if (len > 0) {  
            for (int i = 0; i < len; i++) {  
                char tempStr = targetStr.charAt(i);  
                String data = String.valueOf(tempStr);  
                if (isCN(data)) {  
                    hexStr.append(encodeCN(data));  
                } else {  
                    hexStr.append(encodeStr(data));  
                }  
            }  
        }  
        return hexStr.toString();  
    }  

	public static String intToHex(int value) {
		byte[] b = new byte[4];

		b[0] = ((byte) ((value & 0xFF000000) >>> 24));
		b[1] = ((byte) ((value & 0xFF0000) >>> 16));
		b[2] = ((byte) ((value & 0xFF00) >>> 8));
		b[3] = ((byte) (value & 0xFF));

		return bufferToHex(b);
	}
	
	public static String toHex(String num) {
		String hex = Integer.toHexString(Integer.valueOf(num));
		if (hex.length() % 2 != 0) {
			hex = new StringBuilder().append("0").append(hex).toString();
		}
		return hex.toUpperCase();
	}

	// 字节转16进制
	public static String byte2hex(byte[] data) {
		if (data == null) {
			return "";
		}
		StringBuffer buff = new StringBuffer();
		int len = data.length;
		for (int j = 0; j < len; j++) {
			if ((data[j] & 0xff) < 16) {
				buff.append('0');
			}
			buff.append(Integer.toHexString(data[j] & 0xff));
		}
		return buff.toString();

	}

	// 16进制转字节
	public static byte[] hex2byte(String content) {
		/* 对输入值进行规范化整理 */
		content = content.trim().replace(" ", "").toUpperCase(Locale.US);
		// 处理值初始化
		int m = 0, n = 0;
		int iLen = content.length() / 2; // 计算长度
		byte[] ret = new byte[iLen]; // 分配存储空间

		for (int i = 0; i < iLen; i++) {
			m = i * 2 + 1;
			n = m + 1;
			ret[i] = (byte) (Integer.decode("0x" + content.substring(i * 2, m)
					+ content.substring(m, n)) & 0xFF);
		}
		return ret;

	}

	/**
	 * 字符串转换为字节数组
	 * 
	 * @param string
	 *            字符串 stringToBytes("0710BE8716FB"); return:
	 *            b[0]=0x07;b[1]=0x10;...b[5]=0xfb;
	 */
	public static byte[] stringToBytes(String string) {
		if (string == null || string.length() == 0 || string.length() % 2 != 0) {
			return null;
		}
		int stringLen = string.length();
		byte byteArrayResult[] = new byte[stringLen / 2];
		StringBuffer sb = new StringBuffer(string);
		String strTemp;
		int i = 0;
		while (i < sb.length() - 1) {
			strTemp = string.substring(i, i + 2);
			byteArrayResult[i / 2] = (byte) Integer.parseInt(strTemp, 16);
			i += 2;
		}
		return byteArrayResult;
	}

	public static String bufferToHex(byte[] buffer) {
		StringBuilder res = new StringBuilder();
		for (int i = 0; i < buffer.length; i++) {
			res.append(byteToHex(buffer[i]));
		}
		return res.toString();
	}

	public static String bufferToHex(byte[] buffer, int start, int end) {
		StringBuilder res = new StringBuilder();
		for (int i = start; i < end; i++) {
			res.append(byteToHex(buffer[i]));
		}
		return res.toString();
	}

	public static String byteToHex(byte byteValue) {
		String hs = "";
		String tmp = "";

		tmp = Integer.toHexString(byteValue & 0xFF);
		if (tmp.length() == 1)
			hs = hs + "0" + tmp;
		else {
			hs = hs + tmp;
		}
		tmp = null;
		return hs.toUpperCase();
	}

	public static String toHex(int num) {
		String hex = Integer.toHexString(num);
		if (hex.length() % 2 != 0) {
			hex = "0" + hex;
		}
		return hex.toUpperCase();
	}
	
	public static byte[] hexToBuffer(String hex) {
		if ((hex == null) || ("".equals(hex))) {
			return new byte[0];
		}
		if (hex.length() % 2 != 0) {
			throw new RuntimeException("字符串的长度不为偶数：" + hex);
		}
		int len = hex.length() / 2;
		byte[] byteArray = new byte[len];
		int index = 0;
		for (int i = 0; i < len; i++) {
			byteArray[i] = ((byte) Integer.parseInt(
					hex.substring(index, index + 2), 16));
			index += 2;
		}
		return byteArray;
	}

	public static byte hexToByte(String hex) {
		byte res = 0;

		if (hex.length() != 2) {
			throw new RuntimeException("字符串长度不为2");
		}
		res = (byte) Integer.parseInt(hex, 16);

		return res;
	}
	
	public static String shortToHex(short s) {
		StringBuilder res = new StringBuilder();
		byte b = (byte) ((s & 0xFF00) >>> 8);
		res.append(byteToHex(b));
		b = (byte) (s & 0xFF);
		res.append(byteToHex(b));
		return res.toString();
	}
}
